package A1_贪心算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LC_56合并区间 {
    public static void main(String[] args){
        int[][] intervals= {{2,3},{4,5},{6,7},{8,9},{1,10}};
        int[][] res=merge(intervals);
        System.out.println(res);
    }
    public static int[][] merge(int[][] intervals) {
        if(intervals.length==0)
            return new int[0][];
        Arrays.sort(intervals,(a,b)->Integer.compare(a[0],b[0]));
        List<int[]> result=new ArrayList<>();
        int start=intervals[0][0];
        int maxend=intervals[0][1];
        for(int i=1;i<intervals.length;i++){
            if(intervals[i][0]<=maxend){
                maxend=Math.max(maxend,intervals[i][1]);
            }
            else{
                result.add(new int[]{start,maxend});
                start=intervals[i][0];
                maxend=intervals[i][1];
            }
        }
        result.add(new int[]{start,maxend});
        return result.toArray(new int[result.size()][2]);
    }
}
